package com.hnucm.cooklife.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.hnucm.cooklife.R;
import com.hnucm.cooklife.adapter.CollectAdapter;
import com.hnucm.cooklife.adapter.RecomAdapter;
import com.hnucm.cooklife.adapter.SearchResultAdapter;
import com.hnucm.cooklife.base.BaseFragment;
import com.hnucm.cooklife.base.Utils;
import com.hnucm.cooklife.base.utils.Constant;
import com.hnucm.cooklife.base.utils.LoginUtils;
import com.hnucm.cooklife.bean.base.Event;
import com.hnucm.cooklife.bean.db.Dish;
import com.hnucm.cooklife.bean.me.DishColl;
import com.hnucm.cooklife.bean.me.ToAddCollectData;
import com.hnucm.cooklife.contract.mecollect.Contract;
import com.hnucm.cooklife.presenter.me.MeCollectPresenter;
import com.hnucm.cooklife.ui.activity.DishDetailActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;

public class CoDishFragment extends BaseFragment<Contract.IMeCollectView, MeCollectPresenter> implements Contract.IMeCollectView,
        com.scwang.smartrefresh.layout.listener.OnLoadMoreListener,
        com.scwang.smartrefresh.layout.listener.OnRefreshListener{
    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mPresenter.loadMeCollect(userId);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPresenter.loadMeCollect(userId);
    }

    private Context mContext;
    private CollectAdapter mAdapter;
    private List<DishColl> mDishList = new ArrayList<>();

    private int userId;

    @BindView(R.id.codish_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mSmartRefreshLayout;
    @Override
    protected int getContentViewId() {
        return R.layout.co_dish_fragment;
    }

    @Override
    protected void init() {
        mContext = getContext().getApplicationContext();
        initAdapter();
        userId = LoginUtils.getLoginId();
        mPresenter.loadMeCollect(userId);

        mSmartRefreshLayout.setNestedScrollingEnabled(false);
        mSmartRefreshLayout.setOnLoadMoreListener(this);
        mSmartRefreshLayout.setOnRefreshListener(this);

    }
    private void initAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mAdapter = new CollectAdapter(mContext,mDishList);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new CollectAdapter.onItemClickListener() {
            @Override
            public void onSeleClickListener(View view, int position) {
                Intent intent = new Intent(getActivity(), DishDetailActivity.class);
                intent.putExtra("dishId",mDishList.get(position).dishId);
                DishColl dish = mDishList.get(position);

                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }


    @Override
    protected MeCollectPresenter createPresenter() {
        return new MeCollectPresenter();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event){
        if(event.target == Event.TARGET_MY_COLLECT){
            if(event.type == Event.TYPE_UNCOLLECT){
                Integer dishId = Integer.valueOf(event.data);
                List<DishColl> tempList = mDishList.stream().filter(dish ->
                        dish.dishId != dishId)
                        .collect(Collectors.toList());
                //通知各页面改变收藏状态
                changeCollectState(dishId);
                mDishList.clear();
                mDishList.addAll(tempList);
                mAdapter.setDishList(mDishList);
                mPresenter.unCollect(userId,dishId);
            } else if(event.type == Event.TYPE_COLLECT_STATE_REFRESH){
                Integer dishId = Integer.valueOf(event.data);
                List<DishColl> tempList = mDishList.stream().filter(dish ->
                        dish.dishdone != dishId)
                        .collect(Collectors.toList());
                mDishList.clear();
                mDishList.addAll(tempList);
                mAdapter.setDishList(mDishList);
            }
        }
    }

    private void changeCollectState(Integer dishId) {
        //取消收藏传递给菜谱详情页
        Event dishDetailEvent = new Event();
        dishDetailEvent.target = Event.TARGET_DISH_DETAIL;
        dishDetailEvent.type = Event.TYPE_COLLECT_STATE_REFRESH;
        dishDetailEvent.data = dishId + "";
        EventBus.getDefault().post(dishDetailEvent);

        //取消收藏传递给推荐页
        Event recomEvent = new Event();
        recomEvent.target = Event.TARGET_RECOM;
        recomEvent.type = Event.TYPE_COLLECT_STATE_REFRESH;
        recomEvent.data = dishId + "";
        EventBus.getDefault().post(recomEvent);
    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoadingFailed() {

    }

    @Override
    public void onLoadSuccess() {

        mSmartRefreshLayout.finishLoadMore();
        mSmartRefreshLayout.finishRefresh();
    }

    @Override
    public void onLoadMeCollect(List<DishColl> dishes) {
        mDishList.clear();
        mDishList.addAll(dishes);
        mAdapter.setDishList(mDishList);
    }

    @Override
    public void onRefreshMeCollect(List<DishColl> dishes) {

    }

    @Override
    public void onUnCollect(ToAddCollectData collectData, int dishId) {
        if(collectData != null){
            if(collectData.getCode() == Constant.SUCCESS){
                Utils.showSnackMessage(getActivity(),"取消收藏成功");
            } else {
                ToastUtils.showShort("取消收藏失败");
            }
        }
    }
}
